package com.tywj.buscustomerapp.view.activity;

import android.content.Intent;
import android.media.Image;
import android.net.Uri;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.tywj.buscustomerapp.Config;
import com.tywj.buscustomerapp.R;
import com.tywj.buscustomerapp.model.bean.BaseReqeust;
import com.tywj.buscustomerapp.utils.SPUtils;
import com.tywj.buscustomerapp.utils.ToastUtils;
import com.tywj.buscustomerapp.utils.WebServicrUtils;
import com.tywj.buscustomerapp.view.myview.LoadingDialog;
import com.tywj.buscustomerapp.view.myview.ToastJoe;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class RegisterPhoneCodeActivity extends BaseActivity {
    @BindView(R.id.head_left) ImageView back;
    @BindView(R.id.head_title) TextView title;
    @BindView(R.id.register_edit) EditText editText;
    @BindView(R.id.getCode) TextView getCode;
    @BindView(R.id.phone_number) TextView phoneInfo;
    @BindView(R.id.register_submit) TextView submit;
    @BindView(R.id.register_call) TextView callPc;
    private String phoneNumber;
    private boolean isCanNext= false;
    private Timer timer;
    private TimerTask task;
    private int  recLen = 60;
    private boolean isCanGetCode= true;
    private String code = "";

    @Override
    protected int getContentId() {
        return R.layout.activity_register_phone_code;
    }

    @Override
    protected void initWidget(Bundle savedInstanceState) {
        super.initWidget(savedInstanceState);
        if (getIntent()!=null){
            phoneNumber = getIntent().getStringExtra("phone");
        }else{
            finish();
        }
        title.setText("获取验证码");
        phoneInfo.setText("请输入"+phoneNumber+"收到的验证码");

    }

    private void doGetCode(){
        if (isCanGetCode) {
            startTime();
            RequestQueue requestQueue = Volley.newRequestQueue(RegisterPhoneCodeActivity.this);
            //创建一个请求
            String url =  "http://sms.cd917.com/api/SmsService/SendSms";
            JSONObject object = new JSONObject();
            try {
                int a = (int)(Math.random()*(9999-1000+1))+1000;
                code = a+"";
                Log.i("taylor",code);
                String mes = Config.MSIMG+code;
                object.put("tel",phoneNumber);
                object.put("content",mes);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, object, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject jsonObject) {
                    ToastJoe.getmToastJoe().ToastShowRight(RegisterPhoneCodeActivity.this,null,"验证码发送成功");
                    getCode.setClickable(false);

                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    if (timer!=null){
                        timer.cancel();
                        task.cancel();
                        task=null;
                        timer=null;
                        recLen = 60;
                    }
                    ToastJoe.getmToastJoe().ToastShowRight(RegisterPhoneCodeActivity.this,null,"验证码发送失败");
                }
            });
            //将创建的请求添加到队列中
            requestQueue.add(jsonObjectRequest);
        }
    }

    @Override
    protected void initClick() {
        super.initClick();
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        getCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Observable.create(new ObservableOnSubscribe<String>() {
                    @Override
                    public void subscribe(ObservableEmitter<String> e){
                        try {
                            String mes = WebServicrUtils.getInstance().doCheckRegister(phoneNumber);
                            Log.i("taylor",mes);
                            if (mes.equals("true")){
                                e.onNext(mes);
                            }else {
                                e.onError(null);
                            }
                        } catch (IOException e1) {
                            e.onError(e1);
                            e1.printStackTrace();
                        } catch (XmlPullParserException e1) {
                            e.onError(e1);
                            e1.printStackTrace();
                        }
                    }
                }).subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Observer<String>() {
                            @Override
                            public void onSubscribe(Disposable d) {

                            }

                            @Override
                            public void onNext(String s) {
                                doGetCode();
                            }

                            @Override
                            public void onError(Throwable e) {
                                ToastJoe.getmToastJoe().ToastShow(RegisterPhoneCodeActivity.this,null,"此手机号已为注册用户");
                            }

                            @Override
                            public void onComplete() {
//18000596856
                            }
                        });


            }
        });

        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isCanNext && code.equals(editText.getText().toString())){
                    Intent intent = new Intent(RegisterPhoneCodeActivity.this,RegisterPwdActivity.class);
                    intent.putExtra("phone",phoneNumber);
                    startActivity(intent);
                    finish();
                }else{
                    ToastJoe.getmToastJoe().ToastLongShow(RegisterPhoneCodeActivity.this,null,"验证码错误");
                }
            }
        });

        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                isCanNext = editText.getText().toString().equals(code);
                if (isCanNext  && !code.equals("")) {
                    submit.setBackgroundResource(R.drawable.bg_ori_shape1);
                    submit.setTextColor(getResources().getColor(R.color.text));
                } else {
                    submit.setBackgroundResource(R.drawable.bg_gry_shape11);
                    submit.setTextColor(getResources().getColor(R.color.text_help));
                }
//                if (){
//                    submit.setBackgroundResource(R.drawable.ori_line_shape);
//                    submit.setTextColor(getResources().getColor(R.color.appColor));
//                }else{
//                    submit.setBackgroundResource(R.drawable.gry_shape);
//                    submit.setTextColor(getResources().getColor(R.color.white));
//                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        callPc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                final AlertDialog build = new AlertDialog.Builder(RegisterPhoneCodeActivity.this,R.style.AlertDialogStyle).create();
                //自定义布局
                View view = getLayoutInflater().inflate(R.layout.dialog_layout, null);
                build.setView(view, 0, 0, 0, 0);
                build.show();
                //得到当前显示设备的宽度，单位是像素
                int width = getWindowManager().getDefaultDisplay().getWidth();
                //得到这个dialog界面的参数对象
                WindowManager.LayoutParams params = build.getWindow().getAttributes();
                //设置dialog的界面宽度
                params.width = width-(width/3);
                //设置dialog高度为包裹内容
                params.height =  WindowManager.LayoutParams.WRAP_CONTENT;
                //设置dialog的重心
                params.gravity = Gravity.CENTER;
                build.getWindow().setAttributes(params);
                TextView titleTv = view.findViewById(R.id.message);
                TextView messageTv = view.findViewById(R.id.message1);
                titleTv.setText("拨打客服电话");
                final String number = Config.CALL_NUMBER;
                messageTv.setText(number);
                Button btn_sure = view.findViewById(R.id.yes);
                Button btn_cancel = view.findViewById(R.id.no);
                btn_sure.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"+number));
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                        build.dismiss();
                    }
                });
                btn_cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View arg0) {
                        build.dismiss();
                    }
                });
            }
        });
    }

    private void startTime() {
        isCanGetCode = false;
        timer = new Timer();
        task = new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {      // UI thread
                    @Override
                    public void run() {
                        try{
                            recLen--;
                            getCode.setText(recLen+"秒");
                            if(recLen < 1){
                                timer.cancel();
                                task.cancel();
                                timer =  null;
                                task = null;
                                recLen = 60;
                                getCode.setClickable(true);
                                getCode.setText("获取验证码");
                                isCanGetCode = true;
                            }
                        }catch (Exception e){
                            finish();
                        }
                    }
                });
            }
        };
        timer.schedule(task, 1000, 1000);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer!=null){
            timer.cancel();
            task.cancel();
            timer = null;
            task = null;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("注册2");
        MobclickAgent.onResume(this); //统计时长

    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("注册2");
        MobclickAgent.onPause(this);
    }
}
